import java.io.*;
import java.util.Scanner;

/*
 * @author zzr
 * @date: 2025/04/21  17:29
 * @description:
 */
public class IO13 {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要查询的目录：");
        String rootPath = scanner.next();
        System.out.println("请输入要查询的词语：");
        String word = scanner.next();

        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()) {
            System.out.println("输入的目录有误！");
            return;
        }
        scanDir(rootFile,word);
    }

    private static void scanDir(File rootFile, String word) {
        File[] files = rootFile.listFiles();

        if(null == files) {
            return;
        }

        for (File file : files) {
            System.out.println("当前遍历到" + file.getAbsolutePath());
            if (file.isFile()) {
                searchInFile(file,word);
            } else if (file.isDirectory()) {
                scanDir(file,word);
            } else {
                ;
            }
        }
    }

    private static void searchInFile(File file, String word) {

        try (InputStream inputStream = new FileInputStream(file)) {
            StringBuilder stringBuilder = new StringBuilder();
            byte[] buffer = null;
            while (true) {
                buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if (-1 == n) {
                    break;
                }
                String s = new String(buffer, 0, n);
                stringBuilder.append(s);
            }
            if (-1 == stringBuilder.indexOf(word)) {
                // 没找到
                System.out.println("没找到");
            }
            // 找到了
            System.out.println("找到了" + word + "在" + file.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
